package com.csdn.leon.activity;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import com.csdn.leon.adapter.DragAdapter;
import com.csdn.leon.adapter.OtherAdapter;
import com.csdn.leon.anima.AnimatorUtil;
import com.csdn.leon.base.BaseActivity;
import com.csdn.leon.base.MyApplication;
import com.csdn.leon.broadcast.ConnectionChangeReceiver;
import com.csdn.leon.broadcast.ConnectionChangeReceiver.netEventHandler;
import com.csdn.leon.broadcast.NetBroadcastReceiver;
import com.csdn.leon.cache.LabelManager;
import com.csdn.leon.fragment.BaseFragment;
import com.csdn.leon.fragment.HomeFragment;
import com.csdn.leon.fragment.MyFragmentManager;
import com.csdn.leon.interf.ActivityListener;
import com.csdn.leon.model.LabelModel;
import com.csdn.leon.util.Constants;
import com.csdn.leon.util.DoubleClickExitHelp;
import com.csdn.leon.util.SPUtils;
import com.csdn.leon.util.TDevice;
import com.csdn.leon.view.ColorTextView;
import com.csdn.leon.view.FFViewPager;
import com.csdn.leon.view.NewsTitleTextView;
import com.csdn.leon.view.SegmentControl;
import com.csdn.leon.view.SegmentControl.OnSegmentControlClickListener;
import com.csdn.leon.view.gridview.DragGridView;
import com.csdn.leon.view.gridview.OtherGridView;
import com.csdn.leon.base.R;

import android.R.color;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.view.ViewConfiguration;
import android.view.Window;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * @author kincai
 *
 */
@SuppressLint("NewApi")
public class MainActivity extends BaseActivity implements OnPageChangeListener,
		OnClickListener, ActivityListener, OnSegmentControlClickListener,
		OnItemClickListener, netEventHandler {
	private FFViewPager mViewPager;
	private List<Fragment> mTabs = new ArrayList<Fragment>();
	private FragmentPagerAdapter mAdapter;
	private int mCurrentIndex;
	private TextView left_title;
	private SegmentControl segmentControl;

	private ImageView refreshImg;
	private ImageView mShowLabel;
	private ImageView mHideLabel;

	private LinearLayout viewgroup;
	private LinearLayout mainLayout;
	private ScrollView mScroll;
	RotateAnimation rotateAnimator;

	private int mPreSelectItem;
	private String[] mTitles = new String[] { "博客", "发现", "设置" };

	private List<ColorTextView> mTabIndicator = new ArrayList<ColorTextView>();

	private DragGridView dragGridView;
	private OtherGridView otherGridView;

	DragAdapter dragAdapter;

	OtherAdapter otherAdapter;

	ArrayList<LabelModel> dragChannelList = new ArrayList<LabelModel>();
	ArrayList<LabelModel> otherChannelList = new ArrayList<LabelModel>();
	boolean isMove = false;
	private ConnectionChangeReceiver myReceiver;

	private RelativeLayout title_label;
	private DoubleClickExitHelp mDoubleClickExit;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		IntentFilter filter = new IntentFilter(
				ConnectivityManager.CONNECTIVITY_ACTION);
		myReceiver = new ConnectionChangeReceiver();
		myReceiver.mListeners.add(this);
		this.registerReceiver(myReceiver, filter);

		initView();

		initDatas();
		mViewPager.setScanScroll(false);
		mViewPager.setAdapter(mAdapter);
		mViewPager.setOnPageChangeListener(this);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		this.unregisterReceiver(myReceiver);
	}

	private void initDatas() {
		mainLayout = (LinearLayout) findViewById(R.id.activity_main_layout);
		mScroll = (ScrollView) findViewById(R.id.main_scrollview);
		mShowLabel = (ImageView) findViewById(R.id.show_label);
		mShowLabel.setOnClickListener(this);
		mHideLabel = (ImageView) findViewById(R.id.hide_label);
		mHideLabel.setOnClickListener(this);
		title_label = (RelativeLayout) findViewById(R.id.title_label);
		dragChannelList = ((ArrayList<LabelModel>) LabelManager.getManage(
				MyApplication.getInstance().getSQLHelper()).getUserChannel());
		otherChannelList = ((ArrayList<LabelModel>) LabelManager.getManage(
				MyApplication.getInstance().getSQLHelper()).getOtherChannel());
		dragAdapter = new DragAdapter(this, dragChannelList);
		dragGridView.setAdapter(dragAdapter);
		otherAdapter = new OtherAdapter(this, otherChannelList);
		otherGridView.setAdapter(this.otherAdapter);
		viewgroup = (LinearLayout) findViewById(R.id.viewgroup);
		for (int i = 0; i < mTitles.length; i++) {

			// 官方提示为fragmrnt传数据 使用bundle
			Fragment fragment = MyFragmentManager.getInstance().getFragment(i);
			// HomeFragment homeFragment = new HomeFragment();
			// Bundle args = new Bundle();
			// args.putString(HomeFragment.TITLE, mTitles[i]);
			// fragment.setArguments(args);
			if (null != fragment && fragment instanceof HomeFragment) {
				((HomeFragment) fragment).setActivityListener(this);
			}

			mTabs.add(fragment);
			addLabel();
			int labelPosition = Integer.parseInt(String.valueOf(SPUtils.get(
					MainActivity.this, "label_1", 0)));
			moveTitle(labelPosition);
		}

		mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {

			@Override
			public int getCount() {
				return mTabs.size();
			}

			@Override
			public Fragment getItem(int position) {
				return mTabs.get(position);
			}
		};

		mViewPager.setCurrentItem(0);
		mCurrentIndex = 0;

	}

	// @Override
	// public boolean onCreateOptionsMenu(Menu menu) {
	// getMenuInflater().inflate(R.menu.main, menu);
	// return true;
	// }

	private void initView() {
		mDoubleClickExit = new DoubleClickExitHelp(this);
		dragGridView = (DragGridView) findViewById(R.id.userGridView);
		otherGridView = (OtherGridView) findViewById(R.id.otherGridView);
		dragGridView.setOnItemClickListener(this);
		otherGridView.setOnItemClickListener(this);
		refreshImg = (ImageView) findViewById(R.id.title_right_refresh);
		refreshImg.setOnClickListener(this);
		segmentControl = (SegmentControl) findViewById(R.id.segment_control);
		segmentControl.setVisibility(View.GONE);
		segmentControl.setOnSegmentControlClickListener(this);
		rotateAnimator = AnimatorUtil.getRotateAnimator();

		mViewPager = (FFViewPager) findViewById(R.id.id_viewpager);

		ColorTextView one = (ColorTextView) findViewById(R.id.id_indicator_one);
		ColorTextView two = (ColorTextView) findViewById(R.id.id_indicator_two);
		ColorTextView three = (ColorTextView) findViewById(R.id.id_indicator_three);
		ColorTextView four = (ColorTextView) findViewById(R.id.id_indicator_four);

		mTabIndicator.add(one);
		mTabIndicator.add(two);
		// mTabIndicator.add(three);
		mTabIndicator.add(four);

		one.setOnClickListener(this);
		two.setOnClickListener(this);
		three.setOnClickListener(this);
		four.setOnClickListener(this);

		one.setIconAlpha(1.0f);// 设置了默认的第一个颜色的颜色
	}

	@Override
	public void onPageSelected(int position) {
		if (position == 0) {
			title_label.setVisibility(View.VISIBLE);
		} else {
			title_label.setVisibility(View.GONE);
		}
	}

	/**
	 * positionOffset是设置颜色的
	 */
	@Override
	public void onPageScrolled(int position, float positionOffset,
			int positionOffsetPixels) {// 从第1页到2页的时候 position 始终为0
										// positionOffset从0-1 从第2页到1页的时候
										// position 始终为0 positionOffset从1-0
		// Log.e("TAG", "position = " + position + " , positionOffset = "
		// + positionOffset);

		if (positionOffset > 0) {
			ColorTextView left = mTabIndicator.get(position);
			ColorTextView right = mTabIndicator.get(position + 1);

			left.setIconAlpha(1 - positionOffset);// 变小
			right.setIconAlpha(positionOffset);
		}

	}

	@Override
	public void onPageScrollStateChanged(int state) {

	}

	@Override
	public void onClick(View v) {

		resetOtherTabs();//

		switch (v.getId()) {
		case R.id.id_indicator_one:
			mTabIndicator.get(0).setIconAlpha(1.0f);
			mViewPager.setCurrentItem(0, false);
			title_label.setVisibility(View.VISIBLE);
			// segmentControl.setVisibility(View.VISIBLE);
			// left_title.setText(mTitles[0]);
			mCurrentIndex = 0;
			break;
		case R.id.id_indicator_two:
			mTabIndicator.get(1).setIconAlpha(1.0f);
			mViewPager.setCurrentItem(1, false);
			segmentControl.setVisibility(View.GONE);
			title_label.setVisibility(View.GONE);
			mScroll.setVisibility(View.GONE);
			// left_title.setText(mTitles[1]);
			mCurrentIndex = 1;
			break;
		// case R.id.id_indicator_three:
		// mTabIndicator.get(2).setIconAlpha(1.0f);
		// mViewPager.setCurrentItem(2, false);
		// // left_title.setText(mTitles[2]);
		// mCurrentIndex = 2;
		// break;
		case R.id.id_indicator_four:
			mTabIndicator.get(2).setIconAlpha(1.0f);
			mViewPager.setCurrentItem(2, false);

			// left_title.setText(mTitles[3]);
			mCurrentIndex = 2;
			break;
		case R.id.title_right_refresh:
			// ((HomeFragment) mAdapter.getItem(mCurrentIndex)).onRefresh();
			break;

		case R.id.show_label:
			mTabIndicator.get(0).setIconAlpha(1.0f);
			mainLayout.setVisibility(View.GONE);
			mScroll.setVisibility(View.VISIBLE);
			break;
		case R.id.hide_label:
			mTabIndicator.get(0).setIconAlpha(1.0f);
			mainLayout.setVisibility(View.VISIBLE);
			mScroll.setVisibility(View.GONE);
			addLabel();
			int labelPosition = 0;
			// Integer.parseInt(String.valueOf(SPUtils.get(
			// MainActivity.this, "label_1", 0)));
			moveTitle(labelPosition);
			break;
		}

	}

	protected long lastDown = -1;
	public final static long DOUBLE_TIME = 1000;
	private boolean isLongPressed;

	/**
	 * * 判断是否有长按动作发生 * @param lastX 按下时X坐标 * @param lastY 按下时Y坐标 *
	 * 
	 * @param thisX
	 *            移动时X坐标 *
	 * @param thisY
	 *            移动时Y坐标 *
	 * @param lastDownTime
	 *            按下时间 *
	 * @param thisEventTime
	 *            移动时间 *
	 * @param longPressTime
	 *            判断长按时间的阀值
	 */
	private boolean isLongPressed(float lastX, float lastY, float thisX,
			float thisY, long lastDownTime, long thisEventTime,
			long longPressTime) {
		float offsetX = Math.abs(thisX - lastX);
		float offsetY = Math.abs(thisY - lastY);
		long intervalTime = thisEventTime - lastDownTime;
		if (intervalTime >= longPressTime) {
			return true;
		}
		return false;
	}

	/**
	 *
	 * 
	 * 这个方法是设置每个底部view的颜色
	 */
	private void resetOtherTabs() {
		for (int i = 0; i < mTabIndicator.size(); i++) {
			mTabIndicator.get(i).setIconAlpha(0);// 不是绿色 之前的颜色咯
		}
	}

	// 获取屏幕的宽度
	public static int getScreenWidth(Context context) {
		WindowManager manager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = manager.getDefaultDisplay();
		return display.getWidth();
	}

	public void addLabel() {
		viewgroup.removeAllViews();
		// dragChannelList = ((ArrayList<LabelModel>) LabelManager.getManage(
		// MyApplication.getInstance().getSQLHelper()).getUserChannel());
		List<LabelModel> list = dragAdapter.getChannnelLst();
		int itemWidth = 0;
		for (int i = 0; i < list.size(); i++) {
			LabelModel model = list.get(i);
			NewsTitleTextView tv = new NewsTitleTextView(this);
			if (list.size() < 4) {
				itemWidth = getScreenWidth(MainActivity.this) / list.size();

			} else {

				itemWidth = getScreenWidth(MainActivity.this) / 5;
			}
			tv.setTag(model);
			tv.setWidth(50);
			tv.setSingleLine();
			tv.setTextSize(14);
			tv.setLayoutParams(new LinearLayout.LayoutParams(itemWidth,
					LayoutParams.MATCH_PARENT));
			tv.setText(model.getName());
			tv.setOnClickListener(this);
			tv.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					for (int i = 0; i < viewgroup.getChildCount(); i++) {
						NewsTitleTextView child = (NewsTitleTextView) viewgroup
								.getChildAt(i);
						if (child == v) {
							moveTitle(i);

						}
					}

				}
			});
			viewgroup.addView(tv);
		}

	}

	private void moveTitle(int position) {
		SPUtils.put(MainActivity.this, "label_1", position);
		// 当前点击按钮所有左边的宽度
		int invisibleWidth = 0;
		// HorizontalScrollView的宽度
		int scrollWidth = 0;

		viewgroup.measure(viewgroup.getMeasuredWidth(), -1);
		FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
				viewgroup.getMeasuredWidth(), -1);
		params.gravity = Gravity.CENTER_VERTICAL;
		viewgroup.setLayoutParams(params);
		for (int i = 0; i < viewgroup.getChildCount(); i++) {
			NewsTitleTextView itemView = (NewsTitleTextView) viewgroup
					.getChildAt(i);
			int width = itemView.getMeasuredWidth();
			if (i < position) {
				invisibleWidth += width;
			}
			scrollWidth += width;

			if (position != i) {
				itemView.setTextColor(Color.parseColor("#e0e0e0"));
				itemView.setBackgroundColor("#424242");

			} else {
				itemView.setTextColor(Color.parseColor("#f44336"));
				itemView.setBackgroundColor("#424242");

			}
		}
		// 当前点击按钮的宽度
		int titleWidth = viewgroup.getChildAt(position).getMeasuredWidth();
		int nextTitleWidth = 0;
		if (position > 0) {
			// 当前点击按钮相邻右边按钮的宽度
			nextTitleWidth = position == viewgroup.getChildCount() - 1 ? 0
					: viewgroup.getChildAt(position - 1).getMeasuredWidth();
		}
		int screenWidth = getScreenWidth(MainActivity.this);
		final int move = invisibleWidth - (screenWidth - titleWidth) / 2;

		if (mPreSelectItem < position) {// 向屏幕左边移动
			if ((invisibleWidth + titleWidth + nextTitleWidth) >= (screenWidth / 2)) {

				((HorizontalScrollView) viewgroup.getParent()).setScrollX(move);
			}
		} else {// 向屏幕右边移动
			if ((scrollWidth - invisibleWidth) >= (screenWidth / 2)) {

				((HorizontalScrollView) viewgroup.getParent()).setScrollX(move);
			}
		}
		mPreSelectItem = position;

		BaseFragment baseFragment = MyFragmentManager.getInstance()
				.getFragment(mCurrentIndex);
		if (baseFragment instanceof HomeFragment) {
			((HomeFragment) mTabs.get(mCurrentIndex)).setBlogType(dragAdapter
					.getChannnelLst().get(position).getBlogType());
			if (HomeFragment.mSwipyRefreshLayout != null) {
				((HomeFragment) mTabs.get(mCurrentIndex)).requestData(true);
			}
		}
	}

	@Override
	public void startRefresh() {
		refreshImg.startAnimation(rotateAnimator);

	}

	@Override
	public void completedRefresh() {
		refreshImg.clearAnimation();
	}

	@Override
	public void onSegmentControlClick(int index) {

		switch (index) {
		case 0:
			HomeFragment fragment = (HomeFragment) mAdapter.getItem(0);
			fragment.setNew(false);
			fragment.requestData(false);
			break;
		case 1:
			HomeFragment fragment1 = (HomeFragment) mAdapter.getItem(0);
			fragment1.setNew(true);
			fragment1.requestData(false);
			break;
		}
	}

	private ImageView getView(View view) {
		view.destroyDrawingCache();
		view.setDrawingCacheEnabled(true);
		Bitmap cache = Bitmap.createBitmap(view.getDrawingCache());
		view.setDrawingCacheEnabled(false);
		ImageView iv = new ImageView(this);
		iv.setImageBitmap(cache);
		return iv;
	}

	private void MoveAnim(View moveView, int[] startLocation,
			int[] endLocation, final LabelModel moveChannel,
			final GridView clickGridView) {
		int[] initLocation = new int[2];
		moveView.getLocationInWindow(initLocation);
		final ViewGroup moveViewGroup = getMoveViewGroup();
		final View mMoveView = getMoveView(moveViewGroup, moveView,
				initLocation);
		TranslateAnimation moveAnimation = new TranslateAnimation(
				startLocation[0], endLocation[0], startLocation[1],
				endLocation[1]);
		moveAnimation.setDuration(300L);// ����ʱ��
		// ��������
		AnimationSet moveAnimationSet = new AnimationSet(true);
		moveAnimationSet.setFillAfter(false);// ����Ч��ִ����Ϻ�View���󲻱�������ֹ��λ��
		moveAnimationSet.addAnimation(moveAnimation);
		mMoveView.startAnimation(moveAnimationSet);
		moveAnimationSet.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
				isMove = true;
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				moveViewGroup.removeView(mMoveView);
				if (clickGridView instanceof DragGridView) {
					otherAdapter.setVisible(true);
					otherAdapter.notifyDataSetChanged();
					dragAdapter.remove();
				} else {
					dragAdapter.setVisible(true);
					dragAdapter.notifyDataSetChanged();
					otherAdapter.remove();
				}
				isMove = false;
			}
		});
	}

	private View getMoveView(ViewGroup viewGroup, View view, int[] initLocation) {
		int x = initLocation[0];
		int y = initLocation[1];
		viewGroup.addView(view);
		LinearLayout.LayoutParams mLayoutParams = new LinearLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		mLayoutParams.leftMargin = x;
		mLayoutParams.topMargin = y;
		view.setLayoutParams(mLayoutParams);
		return view;
	}

	/**
	 * �����ƶ���ITEM��Ӧ��ViewGroup��������
	 */
	private ViewGroup getMoveViewGroup() {
		ViewGroup moveViewGroup = (ViewGroup) getWindow().getDecorView();
		LinearLayout moveLinearLayout = new LinearLayout(this);
		moveLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		moveViewGroup.addView(moveLinearLayout);
		return moveLinearLayout;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, final View view,
			final int position, long id) {
		if (isMove) {
			return;
		}
		switch (parent.getId()) {
		case R.id.userGridView:
			// positionΪ 0��1 �Ĳ����Խ����κβ���
			if (position != 0 && position != 1) {
				final ImageView moveImageView = getView(view);
				if (moveImageView != null) {
					TextView newTextView = (TextView) view
							.findViewById(R.id.text_item);
					final int[] startLocation = new int[2];
					newTextView.getLocationInWindow(startLocation);
					final LabelModel channel = ((DragAdapter) parent
							.getAdapter()).getItem(position);
					otherAdapter.setVisible(false);
					otherAdapter.addItem(channel);
					new Handler().postDelayed(new Runnable() {
						public void run() {
							try {
								int[] endLocation = new int[2];
								// ��ȡ�յ�����
								otherGridView.getChildAt(
										otherGridView.getLastVisiblePosition())
										.getLocationInWindow(endLocation);
								MoveAnim(moveImageView, startLocation,
										endLocation, channel, dragGridView);
								dragAdapter.setRemove(position);
							} catch (Exception localException) {
							}
						}
					}, 50L);
				}
			}
			break;
		case R.id.otherGridView:
			final ImageView moveImageView = getView(view);
			if (moveImageView != null) {
				TextView newTextView = (TextView) view
						.findViewById(R.id.text_item);
				final int[] startLocation = new int[2];
				newTextView.getLocationInWindow(startLocation);
				final LabelModel channel = ((OtherAdapter) parent.getAdapter())
						.getItem(position);
				dragAdapter.setVisible(false);
				dragAdapter.addItem(channel);
				new Handler().postDelayed(new Runnable() {
					public void run() {
						try {
							int[] endLocation = new int[2];
							dragGridView.getChildAt(
									dragGridView.getLastVisiblePosition())
									.getLocationInWindow(endLocation);
							MoveAnim(moveImageView, startLocation, endLocation,
									channel, otherGridView);
							otherAdapter.setRemove(position);
						} catch (Exception localException) {
						}
					}
				}, 50L);
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onNetChange() {

		if (TDevice.isNetworkAvailable()) {
		} else {
			Toast.makeText(MainActivity.this, "网络出现故障，请检查网络··", 2000).show();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// 是否退出应用
			if ((boolean) SPUtils.get(this, Constants.KEY_DOUBLE_CLICK_EXIT,
					true)) {
				return mDoubleClickExit.onKeyDown(keyCode, event);
			}
		}
		return super.onKeyDown(keyCode, event);
	}
}
